package cn.yzgy.yzgyoa.common.service.impl;

import cn.yzgy.yzgyoa.common.entity.SysAlarm;
import cn.yzgy.yzgyoa.common.exception.SystemException;
import cn.yzgy.yzgyoa.common.mapper.SysAlarmMapper;
import cn.yzgy.yzgyoa.common.service.ISysAlarmService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Date;

/**
 * <p>
 * 系统异常告警，在系统遇到不正常数据时，会通过此表进行记录 服务实现类
 * </p>
 *
 * @author Yqsen
 * @since 2020-04-07
 */
@Service
public class SysAlarmServiceImpl extends ServiceImpl<SysAlarmMapper, SysAlarm> implements ISysAlarmService {

    /**
     * 保存系统异常
     * @param e 异常对象
     */
    @Async
    public void saveExceptions(SystemException e) {
        saveExceptions(e, String.format("系统异常： 类型：%d(%s) ATTACH_STR:%s", e.getStatusCode().getCode(),
                e.getStatusCode().getMsg(), e.getAttachStr()));
    }



    /**
     * 保存Exception类型的异常
     * @param e 异常对象
     */
    @Async
    public void saveExceptions(Exception e) {
        saveExceptions(e, "");
    }

    /**
     * 保存异常信息
     *
     * @param e 异常信息
     */
    private void saveExceptions(Exception e, String extraMsg) {
        StackTraceElement element = e.getStackTrace()[0];
        String msg1 = String.format("异常消息：%s\n%s\n触发于：%s -> %s : %d \n StackTrace:\n%s", e.getMessage(), extraMsg,
                element.getClassName(), element.getMethodName(), element.getLineNumber(), getErrorInfoFromException(e));
        saveItem(element.getClassName(), element.getMethodName(), msg1);
    }

    /**
     * 保存项目
     * @param className 类名
     * @param methodName 方法名
     * @param errDesc 错误描述
     */
    private void saveItem(String className, String methodName, String errDesc) {
        save(new SysAlarm().setClassName(className).setMethodName(methodName).setErrDesc(errDesc).setGenerateTime(new Date()));
    }

    public static String getErrorInfoFromException(Exception e) {
        try {
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            e.printStackTrace(pw);
            return "\r\n" + sw.toString() + "\r\n";
        } catch (Exception e2) {
            return "转换异常信息错误";
        }
    }
}
